<template>
  <div>
    <!-- 面包鞋导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体区域 -->
    <el-card>
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入关键字"
            v-model="queryInfo.query"
            clearable
            @clear="getAllUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getAllUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addFormVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="this.usersList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="手机"></el-table-column>
        <el-table-column prop="email" label="邮件"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态" width="61">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-row :gutter="10" class="btns">
              <el-tooltip
                effect="dark"
                content="修改用户"
                placement="top"
                :enterable="false"
              >
                <el-col :span="8"
                  ><el-button
                    size="mini"
                    icon="el-icon-edit"
                    type="primary"
                    @click="getUserInfoById(scope.row.id)"
                  ></el-button
                ></el-col>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="删除用户"
                placement="top"
                :enterable="false"
              >
                <el-col :span="8">
                  <el-button
                    size="mini"
                    icon="el-icon-delete"
                    type="danger"
                    @click="removeUserById(scope.row.id)"
                  ></el-button>
                </el-col>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-col :span="8"
                  ><el-button
                    size="mini"
                    icon="el-icon-setting"
                    type="warning"
                    @click="showSetDialog(scope.row)"
                  ></el-button
                ></el-col>
              </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        @size-change="pageSizeChange"
        @current-change="pageNumChange"
        :current-page="this.queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="this.queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total"
      >
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addFormVisible"
        width="50%"
        :close-on-click-modal="false"
        :show-close="false"
        @close="addDialogClose"
      >
        <el-form
          :model="addForm"
          :rules="FormRules"
          label-width="70px"
          ref="addForm"
          :status-icon="true"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model.number="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser">确定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editFormVisible"
        width="50%"
        :close-on-click-modal="false"
        :show-close="false"
        @closed="editDialogClose"
      >
        <el-form
          :model="editForm"
          :rules="FormRules"
          label-width="70px"
          :status-icon="true"
          ref="editForm"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model.number="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editFormVisible = false">取消</el-button>
          <el-button type="primary" @click="editUser">确定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setFormVisible"
        width="50%"
        :close-on-click-modal="false"
        :show-close="false"
        @closed="setDialogClose"
      >
        <div>
          <el-form :model="selectedUserInfo" label-width="100px">
            <el-form-item label="当前用户">
              <el-input v-model="selectedUserInfo.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="当前角色">
              <el-input
                v-model="selectedUserInfo.role_name"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="分配新角色">
              <el-select v-model="selectedRoleId" placeholder="请选择">
                <el-option
                  v-for="item in rolesList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                  :disabled="item.roleName == selectedUserInfo.role_name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setFormVisible = false">取消</el-button>
          <el-button type="primary" @click="setUser">确定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    var checkMobile = (rule, value, cb) => {
      // 定义正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[0-9]|17[6-8]|18[0-9]|14[57])[0-9]{8}$/;
      // 测试是否匹配，不匹配则返回错误
      if (regMobile.test(value)) return cb();
      cb(new Error("请输入正确格式的手机"));
    };
    return {
      // 搜索信息
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      // 结果总数
      total: 0,
      // 所有用户列表
      usersList: [],
      addFormVisible: false,
      // 添加用户的信息
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 表单验证规则
      FormRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 3,
            max: 10,
            message: "长度在3-10字符之间",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 15,
            message: "长度在6-15字符之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            type: "email",
            message: "请输入正确格式的邮箱",
            trigger: ["change", "blur"],
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机",
            trigger: "blur",
          },
          {
            validator: checkMobile,
            trigger: ["change", "blur"],
          },
        ],
      },
      editFormVisible: false,
      // 用户的修改信息
      editForm: {},
      setFormVisible: false,
      // 被选中的用户
      selectedUserInfo: {},
      // 所有角色列表
      rolesList: [],
      // 被选中的角色的id
      selectedRoleId: "",
    };
  },
  methods: {
    async getUsersList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.usersList = res.data.users;
      this.total = res.data.total;
    },
    pageSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUsersList();
    },
    pageNumChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUsersList();
    },
    async userStateChange(userinfo) {
      // console.log(userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.msg;
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
    },
    getAllUsersList() {
      // 重置页数为第一页
      this.queryInfo.pagenum = 1;
      this.getUsersList();
    },
    addDialogClose() {
      //重置表单
      this.$refs.addForm.resetFields();
    },
    addUser() {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        //关闭对话框
        this.addFormVisible = false;
        //刷新用户列表
        this.getUsersList();
      });
    },
    async getUserInfoById(id) {
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.editForm = res.data;
      this.editFormVisible = true;
    },
    editUser() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        //关闭对话框
        this.editFormVisible = false;
        // 刷新列表
        this.getUsersList();
        this.$message.success(res.meta.msg);
      });
    },
    editDialogClose() {
      this.$refs.editForm.resetFields(); //此处有Bug，验证结果没有移除
    },
    removeUserById(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("users/" + id);
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.$message.success(res.meta.msg);
          this.getAllUsersList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      // console.log(id);
    },
    async showSetDialog(userinfo) {
      // 获取选中的用户
      this.selectedUserInfo = userinfo;
      // 获取所有角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
      // 显示对话框
      this.setFormVisible = true;
    },
    // 提交设置
    async setUser() {
      // 判断有无选择新角色，没有则提示并return
      if (!this.selectedRoleId) return this.$message.error("请选择新角色！");

      // 提交设置
      const { data: res } = await this.$http.put(
        `users/${this.selectedUserInfo.id}/role`,
        { rid: this.selectedRoleId }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);

      this.$message.success(res.meta.msg);
      this.setFormVisible = false;

      this.getUsersList();
    },
    setDialogClose() {
      // 初始化
      this.selectedRoleId = "";
    },
  },
  created() {
    this.getUsersList();
  },
};
</script>
<style lang='less' scoped>
.btns {
  text-align: center;
}
</style>